
#include <BFont>
#include <BStyle>
#include <BTreeWidget>
#include "member_BTreeItem.h"
#include "member_BTreeWidget.h"

using namespace BWE;

#define tree_member(tree)		((member_BTreeWidget*)((BTreeWidget*)tree)->_ptr)
#define item_member(item)		((member_BTreeItem*)((BTreeItem*)item)->_ptr)

member_BTreeItem::member_BTreeItem(BTreeItem* treeItem)
{
	boss = treeItem;
	tree = 0;
	parent = 0;
	dirty = true;
	expanded = true;
	selected = false;
	visible = true;
	ia_form = Form_IconText;
	ia_align = Align_Center;
	indent = 0;
	realFont = 0;
	graph = Graph_None;
	form = Form_None;
}
member_BTreeItem::~member_BTreeItem()
{

}

void member_BTreeItem::attach(BTreeWidget* treeWidget)
{
	if (tree == treeWidget)
		return;
	tree = treeWidget;
	if (tree)
	{
		dirty = true;
		selected = false;
		tree->addChild(widget);
		for (int i = 0; i < children.size(); i++)
		{
			BTreeItem* item = children[i];
			item_member(item)->attach(tree);
		}
	}
}
void member_BTreeItem::detach(BTreeWidget* treeWidget)
{
	if (tree != treeWidget)
		return;
	if (tree)
	{
		if (widget)
			tree->removeChild(widget);
		for (int i = 0; i < children.size(); i++)
		{
			BTreeItem* item = children[i];
			item_member(item)->detach(tree);
		}
		tree_member(tree)->visualItems.remove(boss);
		tree_member(tree)->selectedItems.remove(boss);
		if (tree_member(tree)->hoveredItem == boss)
			tree_member(tree)->hoveredItem = 0;
	}
	tree = 0;
}

void member_BTreeItem::dirtyTree()
{
	if (tree)
	{
		tree_member(tree)->dirty = true;
		tree->fresh();
	}
}

void member_BTreeItem::freshSize(const BStyle* style, const BFont* font, int indent)
{
	this->indent = indent;
	if (widget)
	{
		sizeHint = widget->sizeHint() + BSize(indent, 0);
	}
	else
	{
		ia_form = tree_member(tree)->itemForm;
		if (form)
			ia_form = form;
		ia_imageSize = iconSize;
		if (ia_imageSize.width() < 1)
			ia_imageSize.width() = tree_member(tree)->iconSize.width();
		if (ia_imageSize.height() < 1)
			ia_imageSize.height() = tree_member(tree)->iconSize.height();
		realFont = font;
		if (localFont)
			realFont = localFont;
		if (style)
			realFont = style->font();
		if (realFont)
		{
			ia_textSize = realFont->textSize(text);
			if (ia_imageSize.width() < 1)
				ia_imageSize.width() = realFont->size();
			if (ia_imageSize.height() < 1)
				ia_imageSize.height() = realFont->size();
		}
		adjust(BRect());
		sizeHint = ia_hintSize;
	}
	sizeHint.width() += indent;
	sizeHint.width() += ia_imageSize.width();
	dirty = false;
}
void member_BTreeItem::adjustRect(const BRect& abRect)
{
	if (!tree)
		return;
	arrowArea.setPos(abRect.left() + indent, abRect.top());
	arrowArea.setSize(ia_imageSize);
	arrowRect = arrowArea.align(tree_member(tree)->arrowAlign, tree_member(tree)->realArrowSize);
	BRect alignRect = abRect;
	alignRect.left() = arrowArea.right();
	adjust(alignRect);
	if (widget)
	{
		widget->setRect(alignRect);
	}
}
